package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.entity.CustomerInfo;
import org.example.entity.CustomerOrder;
import org.example.entity.CustomerRepayPlan;
import org.example.service.LoanDataGenerationService;
import org.example.service.LoanDataGenerationService.GenerationResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 贷款数据生成控制器
 * 基于分配计划生成具体的客户、订单和还款计划数据
 */
@Slf4j
@RestController
@RequestMapping("/loan/generation")
public class LoanDataGenerationController {

    private static final Logger log = LoggerFactory.getLogger(LoanDataGenerationController.class);

    @Autowired
    private LoanDataGenerationService loanDataGenerationService;

    /**
     * 生成完整的贷款数据
     */
    @GetMapping("/full")
    public Map<String, Object> generateFullData() {
        log.info("开始生成完整贷款数据");

        try {
            GenerationResult result = loanDataGenerationService.generateLoanData();

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "数据生成并入库成功");
            response.put("customerCount", result.getCustomerInfoList().size());
            response.put("orderCount", result.getOrderList().size());
            response.put("repayPlanCount", result.getRepayPlanList().size());
            response.put("customerInserted", result.getCustomerInserted());
            response.put("orderInserted", result.getOrderInserted());
            response.put("repayPlanInserted", result.getRepayPlanInserted());
            response.put("duration", result.getDuration() + "ms");

            // 返回前10条数据作为示例
            response.put("sampleCustomers", result.getCustomerInfoList().stream().limit(10).toList());
            response.put("sampleOrders", result.getOrderList().stream().limit(10).toList());
            response.put("sampleRepayPlans", result.getRepayPlanList().stream().limit(10).toList());

            return response;
        } catch (Exception e) {
            log.error("生成数据失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "生成失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 生成测试数据（指定订单数量）
     */
    @GetMapping("/test/{count}")
    public Map<String, Object> generateTestData(@PathVariable Integer count) {
        log.info("生成测试数据，订单数: {}", count);

        if (count <= 0 || count > 1000) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "订单数量必须在1-1000之间");
            return response;
        }

        try {
            GenerationResult result = loanDataGenerationService.generateTestData(count);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "测试数据生成成功");
            response.put("customerCount", result.getCustomerInfoList().size());
            response.put("orderCount", result.getOrderList().size());
            response.put("repayPlanCount", result.getRepayPlanList().size());

            // 返回所有数据（因为数量不大）
            response.put("customers", result.getCustomerInfoList());
            response.put("orders", result.getOrderList());
            response.put("repayPlans", result.getRepayPlanList());

            return response;
        } catch (Exception e) {
            log.error("生成测试数据失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "生成失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 预览生成计划（不实际生成数据，只返回统计信息）
     */
    @GetMapping("/preview")
    public Map<String, Object> previewGeneration() {
        log.info("预览生成计划");

        try {
            // 这里只生成少量数据用于预览
            GenerationResult result = loanDataGenerationService.generateTestData(10);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "预览数据已生成");

            // 客户信息示例
            if (!result.getCustomerInfoList().isEmpty()) {
                CustomerInfo customer = result.getCustomerInfoList().get(0);
                Map<String, Object> customerSample = new HashMap<>();
                customerSample.put("plName", customer.getPlName());
                customerSample.put("plPhone", customer.getPlPhone());
                customerSample.put("gender", customer.getGender());
                customerSample.put("age", customer.getAge());
                customerSample.put("city", customer.getSaleCityName());
                customerSample.put("education", customer.getEducation());
                response.put("customerSample", customerSample);
            }

            // 订单示例
            if (!result.getOrderList().isEmpty()) {
                CustomerOrder order = result.getOrderList().get(0);
                Map<String, Object> orderSample = new HashMap<>();
                orderSample.put("orderNo", order.getOrderNo());
                orderSample.put("loanAmount", order.getLoanAmount());
                orderSample.put("loanTerm", order.getLoanTerm());
                orderSample.put("productName", order.getProductName());
                orderSample.put("frTime", order.getFrTime());
                orderSample.put("status", order.getStatus());
                response.put("orderSample", orderSample);
            }

            // 还款计划示例
            if (!result.getRepayPlanList().isEmpty()) {
                CustomerRepayPlan plan = result.getRepayPlanList().get(0);
                Map<String, Object> planSample = new HashMap<>();
                planSample.put("billId", plan.getBillId());
                planSample.put("billTenor", plan.getBillTenor());
                planSample.put("dueDate", plan.getDueDate());
                planSample.put("nowPayPrincipal", plan.getNowPayPrincipal());
                planSample.put("nowPayInterest", plan.getNowPayInterest());
                planSample.put("nowPayAmount", plan.getNowPayAmount());
                planSample.put("repayStatus", plan.getRepayStatus());
                response.put("repayPlanSample", planSample);
            }

            return response;
        } catch (Exception e) {
            log.error("预览失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "预览失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 获取数据生成说明
     */
    @GetMapping("/info")
    public Map<String, Object> getInfo() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("description", "贷款数据生成服务");

        Map<String, Object> rules = new HashMap<>();
        rules.put("总放款金额", "5000万元");
        rules.put("每笔平均额度", "5000元");
        rules.put("时间范围", "2023年7月至2025年9月");
        rules.put("放款策略", "每月递增爬坡");
        rules.put("特殊月份", "1月50%、2月30%、3月20%");
        rules.put("逾期率", "总体7%，2月9%");
        rules.put("逾期规律", "前6期递增，第7期后稳定");

        response.put("businessRules", rules);

        Map<String, String> apis = new HashMap<>();
        apis.put("生成完整数据", "GET /loan/generation/full");
        apis.put("生成测试数据", "GET /loan/generation/test/{count}");
        apis.put("预览生成", "GET /loan/generation/preview");

        response.put("apis", apis);

        return response;
    }
}

